package com.pachong.android.baseuicomponent.refreshable.pullrefresh;

import android.content.Context;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;

/**
 * Created by li on 2015/9/25.
 */
public class PullableRecycleView extends RecyclerView implements Pullable {

    public PullableRecycleView(Context context) {
        super(context);
    }

    public PullableRecycleView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public PullableRecycleView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean canPullDown() {
        LinearLayoutManager layoutManager = null;
        if (getLayoutManager() instanceof LinearLayoutManager || getLayoutManager() instanceof GridLayoutManager) {
            layoutManager = (LinearLayoutManager) getLayoutManager();
        }
        if (layoutManager != null) {
            if (getAdapter().getItemCount() == 0) {
                // 没有item的时候也可以下拉刷新
                return true;
            } else if (layoutManager.findFirstVisibleItemPosition() == 0 && getChildAt(0).getTop() >= 0) {
                // 滑到ListView的顶部了
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean canPullUp() {
        LinearLayoutManager layoutManager = null;
        if (getLayoutManager() instanceof LinearLayoutManager || getLayoutManager() instanceof GridLayoutManager) {
            layoutManager = (LinearLayoutManager) getLayoutManager();
        }
        if (layoutManager != null) {
            if (getAdapter().getItemCount() == 0) {
                // 没有item的时候也可以上拉加载
                return true;
            } else if (layoutManager.findLastVisibleItemPosition() == (getAdapter().getItemCount() - 1)) {
                // 滑到底部了
                int firstVisiblePosition = layoutManager.findFirstVisibleItemPosition();
                int lastVisiblePosition = layoutManager.findLastVisibleItemPosition();
                if (getChildAt(lastVisiblePosition - firstVisiblePosition) != null
                        && getChildAt(lastVisiblePosition - firstVisiblePosition).getBottom() <= getMeasuredHeight())
                    return true;
            }
        }
        return false;
    }


}
